'use client';

import { useState } from 'react';
import { useRouter } from 'next/navigation';
import { signIn } from 'next-auth/react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Card } from '@/components/ui/card';

/**
 * 紧急登录页面
 * 仅用于调试目的，提供简化的登录流程
 */
export default function EmergencyLoginPage() {
  const [email, setEmail] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [debugInfo, setDebugInfo] = useState<string>('');
  const router = useRouter();

  // 显示调试信息
  const logDebug = (message: string) => {
    setDebugInfo(prev => `${new Date().toISOString()}: ${message}\n${prev}`);
    console.log(`[EmergencyLogin] ${message}`);
  };

  // 使用Credentials尝试登录
  const handleTestLogin = async () => {
    setIsLoading(true);
    logDebug(`尝试使用邮箱 ${email} 登录`);

    try {
      // 尝试直接登录
      await signIn('credentials', {
        redirect: false,
        email,
        // 使用固定密码 "password" 测试
        password: 'password',
      });

      logDebug('登录尝试完成，刷新页面检查状态');
      
      // 刷新页面以更新登录状态
      router.refresh();
      
      // 短暂延迟后重定向到仪表盘
      setTimeout(() => {
        logDebug('重定向到仪表盘');
        router.push('/dashboard');
      }, 2000);
    } catch (error: any) {
      logDebug(`登录错误: ${error?.message || '未知错误'}`);
    } finally {
      setIsLoading(false);
    }
  };

  // 测试重定向
  const handleTestRedirect = async () => {
    setIsLoading(true);
    logDebug('测试重定向到仪表盘');
    
    try {
      router.push('/dashboard');
    } catch (error: any) {
      logDebug(`重定向错误: ${error?.message || '未知错误'}`);
      setIsLoading(false);
    }
  };

  // 清除Cookie
  const handleClearCookies = () => {
    logDebug('尝试清除认证Cookie');
    
    // 设置过期的Cookie来删除它们
    document.cookie = 'next-auth.session-token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    document.cookie = '__Secure-next-auth.session-token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure;';
    document.cookie = '__Host-next-auth.session-token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/; secure;';
    document.cookie = 'next-auth.csrf-token=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    document.cookie = 'next-auth.callback-url=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
    
    logDebug('Cookie已清除，刷新页面');
    router.refresh();
  };

  return (
    <div className="flex min-h-screen items-center justify-center p-4">
      <Card className="w-full max-w-md p-6 space-y-6">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-red-500">紧急登录页面</h1>
          <p className="text-sm text-gray-500 mt-2">此页面仅用于调试目的</p>
        </div>

        <div className="space-y-4">
          <div className="space-y-2">
            <label className="text-sm font-medium">测试邮箱</label>
            <Input
              type="email"
              placeholder="输入任意邮箱进行测试"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
            />
            <p className="text-xs text-gray-500">
              任何邮箱都可以，测试时使用固定密码 "password"
            </p>
          </div>
          
          <div className="grid grid-cols-1 gap-2">
            <Button 
              onClick={handleTestLogin}
              disabled={isLoading || !email}
              className="w-full bg-amber-500 hover:bg-amber-600"
            >
              测试登录流程
            </Button>
            
            <Button 
              onClick={handleTestRedirect}
              disabled={isLoading}
              className="w-full bg-blue-500 hover:bg-blue-600"
            >
              测试重定向
            </Button>
            
            <Button 
              onClick={handleClearCookies}
              disabled={isLoading}
              variant="outline"
              className="w-full border-red-500 text-red-500 hover:bg-red-50"
            >
              清除登录Cookie
            </Button>
          </div>
        </div>
        
        <div className="mt-6 pt-4 border-t border-gray-200">
          <h3 className="text-sm font-medium mb-2">调试日志</h3>
          <pre className="bg-gray-100 p-2 rounded text-xs font-mono h-40 overflow-auto">
            {debugInfo || '无调试信息'}
          </pre>
        </div>
      </Card>
    </div>
  );
} 